﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SaleSoft.Models;
using SaleSoft.Helper;

namespace SaleSoft.Areas.administrator.Controllers
{
    public class BannerController : BaseController {
        #region Properties Section
        private SaleSoftEntities db = new SaleSoftEntities();
        #endregion

        #region Views Section
        public ViewResult Index()
        {
            var ds_banner = db.ds_banner.Include("loai_banner");
            return View(ds_banner.ToList());
        }

        public ActionResult Create()
        {
            ViewBag.id_loaibanner = SelectListHelper.DSLoaiBanner(null);
            ViewBag.id_trangthai = SelectListHelper.DSTrangThai(4, null);
            return View();
        }

        public ActionResult Edit ( int id ) {
            ds_banner ds_banner = db.ds_banner.Single(d => d.id_banner == id);
            ViewBag.id_loaibanner = SelectListHelper.DSLoaiBanner(ds_banner.id_loaibanner);
            ViewBag.id_trangthai = SelectListHelper.DSTrangThai(4, ds_banner.id_trangthai);
            return View(ds_banner);
        }
        #endregion

        #region CRUD Section

        [HttpPost]
        public ActionResult Create ( ds_banner ds_banner, HttpPostedFileBase img )
        {
            if (ModelState.IsValid)
            {
                //Save image: accept png and jpg file only
                if (img != null && img.ContentLength > 0) {
                    if (img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".jpg" && img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".png") {
                        ViewData["error"] = "Accept JPGE and PNG file only";
                        return View(ds_banner);
                    }
                    string dt = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
                    string fName = ObjectHelper.ConvertToUnSign(ds_banner.tenbanner) + dt + img.FileName.Substring(img.FileName.LastIndexOf("."));
                    string SaveLocation = Server.MapPath("~\\UploadImages\\");
                    try {
                        img.SaveAs(SaveLocation + fName);   //save new file
                        ds_banner.hinhbanner = fName;              //save file name to entity                    
                    } catch (Exception e) { ViewData["error"] = e.Message; return View(ds_banner); }
                }

                db.ds_banner.AddObject(ds_banner);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }
            ViewBag.id_trangthai = SelectListHelper.DSTrangThai(4, ds_banner.id_trangthai);
            ViewBag.id_loaibanner = SelectListHelper.DSLoaiBanner(ds_banner.id_loaibanner);
            return View(ds_banner);
        }

        [HttpPost]
        public ActionResult Edit ( [Bind(Exclude = "hinhbanner")]ds_banner ds_banner, HttpPostedFileBase img ) {
            if (ModelState.IsValid) {
                ds_banner old = db.ds_banner.Single(p => p.id_banner == ds_banner.id_banner);
                db.ds_banner.Detach(old);
                if (img == null || img.ContentLength == 0) { // khong lam gi ca
                    ds_banner.hinhbanner = old.hinhbanner;
                } else if (old.hinhbanner == null && img != null && img.ContentLength > 0) { // hinh cu khong co, luu hinh moi
                    //save image
                    if (img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".jpg" && img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".png") {
                        ViewData["error"] = "Accept JPGE and PNG file only";
                        return View(ds_banner);
                    }
                    string dt = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
                    string fName = ObjectHelper.ConvertToUnSign(img.FileName) + dt + img.FileName.Substring(img.FileName.LastIndexOf("."));
                    string SaveLocation = Server.MapPath("~\\UploadImages\\");
                    try {
                        img.SaveAs(SaveLocation + fName);   //save new file
                        ds_banner.hinhbanner = fName;              //save file name to entity                    
                    } catch (Exception e) { ViewData["error"] = e.Message; return View(ds_banner); }
                } else if (old.hinhbanner != null && img != null && img.ContentLength > 0) { // co hinh cu, co hinh moi 
                    string oldFile = Server.MapPath("/UploadImages/") + old.hinhbanner;
                    //xoa file cu
                    if (System.IO.File.Exists(oldFile)) {
                        try {
                            System.IO.File.Delete(oldFile);
                        } catch (Exception) {
                        }
                    }
                    //luu file moi
                    if (img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".jpg" && img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".png") {
                        ViewData["error"] = "Accept JPGE and PNG file only";
                        return View(ds_banner);
                    }
                    string dt = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
                    string fName = ObjectHelper.ConvertToUnSign(ds_banner.tenbanner) + dt + img.FileName.Substring(img.FileName.LastIndexOf("."));
                    string SaveLocation = Server.MapPath("~\\UploadImages\\");
                    try {
                        img.SaveAs(SaveLocation + fName);   //save new file
                        ds_banner.hinhbanner = fName;              //save file name to entity                    
                    } catch (Exception e) { ViewData["error"] = e.Message; return View(ds_banner); }
                }

                db.ds_banner.Attach(ds_banner);
                db.ObjectStateManager.ChangeObjectState(ds_banner, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.id_trangthai = SelectListHelper.DSTrangThai(4, ds_banner.id_trangthai);
            ViewBag.id_loaibanner = SelectListHelper.DSLoaiBanner(ds_banner.id_loaibanner);
            return View(ds_banner);
        }

        public ActionResult Delete ( int id ) {
            
            ds_banner ds_banner = db.ds_banner.Single(d => d.id_banner == id);
            //Xoa hinh
            string filePath = Server.MapPath("~\\UploadImages\\") + ds_banner.hinhbanner;
            if (System.IO.File.Exists(filePath)) {
                try {
                    System.IO.File.Delete(filePath);
                } catch (Exception) {
                }
            }
            //Xoa banner khoi db
            db.ds_banner.DeleteObject(ds_banner);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        #endregion

        #region Additional Section

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        #endregion
    }
}